<?php
namespace GuessStar\Controller;
use  Common\Controller\GuessStarController;
class IndexController extends GuessStarController {

    public function __construct()
    {
        $sessionid = 'PHPSESSID='.$this->getSessionId();

        $getsessionid = $_SERVER['HTTP_COOKIE'];
        if ($sessionid!=$getsessionid){
            $this->returnData('','状态已过期请重新授权',400);
        }
    }

    /**
     * 首页数据
     */
    public function getinfo(){

        $member_id = I('post.member_id','','int');
        $appid = I('post.appid','','htmlspecialchars');

        if (!$member_id){
            $this->returnData('','参数不能为空',401);
        }

        $myinfo     =   M('star_member')->field('star_member_id,nickName,avatarUrl,customs,money')->where(array('star_member_id'=>$member_id))->find();
        

        //我的朋友数据
        $my_friend      =   M('star_relationship')->field('coupling_member_id')->where(array('my_member_id'=>$member_id))->select();
        $other_friend   =   M('star_relationship')->field('my_member_id')->where(array('coupling_member_id'=>$member_id))->select();

        $friend_list    =   array();
        if (! empty($my_friend)) 
        {
            foreach ($my_friend as $key => $val) 
            {
                $friend_list[$val['coupling_member_id']]  =   $val['coupling_member_id'];
            }

        }

        if (! empty($other_friend)) 
        {
            foreach ($other_friend as $keys => $vals) 
            {
                $friend_list[$vals['my_member_id']]  =   $vals['my_member_id'];
            }
        }



        //用户数据
        $data['user_data']      =   $myinfo;
        
        //排名数据
        $data['rank']           =   array();
        
        //好友排行
        $data['friend_before']  =   array();
        $data['friend_after']   =   array();
        $before_where   =   array();
        $after_where    =   array();
        if (! empty($friend_list)) 
        {
            $before_where['star_member_id'] = array('in',$friend_list);
            $after_where['star_member_id']  = array('in',$friend_list);

            $before_where['customs']  =   array('lt',$myinfo['customs']);
            $after_where['customs']   =   array('gt',$myinfo['customs']);

            $data['friend_before']  =   M('star_member')->field('star_member_id,nickName,avatarUrl,customs')->where($before_where)->find();
            $data['friend_after']   =   M('star_member')->field('star_member_id,nickName,avatarUrl,customs')->where($after_where)->find();
        }

        //规则图片
        $data['rule'] = array(
            'title'=>'猜明星。',
            'img'=>'',
        );

        
        //其他游戏入口
        $data['games_data']     =   $this->get_games_data();

        //奖品列表
        $data['gift_data']      =   $this->get_gift_data();

        //获奖名单
        $data['winner_list']    =   $this->get_winner_data();   


    
        $this->returnData($data,'成功',200);
    }

    /**
     * 广告
     */
    public function advertising(){

        //广告
        $data  =   $this->get_ad_data();
        $this->returnData($data,'成功',200);

    }

    /**
     * 更多好玩
     */
    public function morepaly(){

        //更多好玩
        $data['more_data']      =   $this->get_more_data();

        $this->returnData($data);

    }

    /**
     * 获取分享内容模板
     */

    public function getsharecontent(){

        $data = array(
            'title'=>'猜明星！',
            'desc'=>'猜明星！',
            'imgUrl'=>'http://oss.beikg.cn/share/share.jpg',
        );

        $this->returnData($data);
    }



    /**
     * 获取设置的参数
     */
    public function getsetinfo(){

        $appid = I('post.appid','','htmlspecialchars');

        if (!$appid){
            $this->returnData('','参数不能为空',401);
        }
        $max = M('star_question')->max('sort');
        $setinfo = M('star_money')->field('star_money_id,appid',true)->where(array('appid'=>$appid))->find();

        $setinfo['sharegroup'] = (int)$setinfo['sharegroup'];
        $setinfo['answer'] = (int)$setinfo['answer'];
        $setinfo['wrong'] = (int)$setinfo['wrong'];
        $setinfo['sharefrend'] = (int)$setinfo['sharefrend'];
        $setinfo['time'] = (int)$setinfo['time'];
        $setinfo['resurgence'] = (int)$setinfo['resurgence'];
        $setinfo['sort'] = (int)$max;

        $this->returnData($setinfo);

    }

    /**
     * 复活
     */
    public function resurgence(){

        $member_id = I('post.member_id','','int');

        $appid = I('post.appid','','htmlspecialchars');

        $encryptedData = $_POST['encryptedData'];
        $iv = $_POST['iv'];

        if (!$member_id){
            $this->returnData('','参数不能为空',401);
        }

        $info = M('star_member')->field('appid,session_key')->where(array('star_member_id'=>$member_id))->find();

        $appid = $info['appid'];
        $sessionkey = $info['session_key'];
        //解析openGId
        $openGId = $this->getopenGId($appid,$sessionkey,$encryptedData,$iv);

        if ($openGId=='-1'){
            $this->returnData('','分享失败',100);
        }

        $time = date('Y-m-d',time());

        $where['sharetime'] = $time;
        $where['star_member_id'] = $member_id;
        $where['openGId'] = $openGId;
        $where['appid'] = $appid;

        $record = "";
        $record = M('star_wechat_group')->where($where)->getField('sharenum'); //判断是否已分享

        //如果分享超过2次则自增分享次数然后返回
        if ($record>=2){
            M('star_wechat_group')->where($where)->setInc('sharenum');
            $this->returnData(array('enough'=>'no'),'今天该群已分享2次',201);
        }


        if (!$record||empty($record)) {
            //如果没分享过则插入，用户复活
            $data = array(
                'openGId' => $openGId,
                'sharetime' => $time,
                'sharenum' => 1,
                'star_member_id' => $member_id,
                'appid' => $appid,
            );

            M('star_wechat_group')->data($data)->add();
            $this->returnData(array('enough'=>'yes'),'立即复活',200);

        }

        //没超出2次
        if ($record<2&&!empty($record)){
            M('star_wechat_group')->where($where)->setInc('sharenum');
            $this->returnData(array('enough'=>'yes'),'立即复活',200);
        }

    }


    /**
     * 微信分享记录
     */
    public function sharerecord(){

        $member_id = I('post.member_id','','int');
        $shareType = I('post.shareType','2','int');
        $encryptedData = $_POST['encryptedData'];
        $iv = $_POST['iv'];
        $appid = I('post.appid','','htmlspecialchars');

        if (!$member_id){
            $this->returnData('','参数错误',401);
        }

        $setinfo = M('star_money')->field('sharegroup,sharefrend')->where(array('appid'=>$appid))->find();

        $setinfo['sharegroup'] = (int)$setinfo['sharegroup'];
        $setinfo['sharefrend'] = (int)$setinfo['sharefrend'];
        //分享好友
        if ($shareType=='2'){
            M('star_member')->where(array('star_member_id'=>$member_id))->setInc('money',$setinfo['sharefrend']);
            $mymoney =  M('star_member')->where(array('star_member_id'=>$member_id))->getField('money');
            $frend['money'] = $mymoney;
            $frend['repetition'] = 'no';
            $this->returnData($frend,'分享成功',200);
        }

        if (!$encryptedData||!$member_id||!$iv){
            $this->returnData('','参数错误',401);
        }


        $info = M('star_member')->field('appid,session_key')->where(array('star_member_id'=>$member_id))->find();

        $appid = $info['appid'];
        $sessionkey = $info['session_key'];
        //解析openGId
        $openGId = $this->getopenGId($appid,$sessionkey,$encryptedData,$iv);

        if ($openGId=='-1'){
            $this->returnData('','分享失败',100);
        }

        $time = date('Y-m-d',time());

        $where['sharetime'] = $time;
        $where['star_member_id'] = $member_id;
        $where['openGId'] = $openGId;
        $where['appid'] = $appid;

        $record = "";
        $record = M('star_wechat_group')->where($where)->getField('sharenum'); //判断是否已分享

        //如果分享超过2次则自增分享次数然后返回
        if ($record>=2){
            M('star_wechat_group')->where($where)->setInc('sharenum');

            $this->returnData(array('repetition'=>'out'),'今天该群已分享3次',201);
        }

        if (!$record||empty($record)){
            //如果没分享过则插入，用户增加100金币
            $add = array(
                'openGId'=>$openGId,
                'sharetime'=>$time,
                'sharenum'=>1,
                'star_member_id'=>$member_id,
                'appid'=>$appid,
            );

            M('star_wechat_group')->data($add)->add();
            M('star_member')->where(array('star_member_id'=>$member_id))->setInc('money',$setinfo['sharegroup']);

            $mymoney =  M('star_member')->where(array('star_member_id'=>$member_id))->getField('money');
            $data['money'] = $mymoney;
            $data['repetition'] = 'no';
            $this->returnData($data,'分享成功',200);
        }

        //没超出2次
        if ($record<2&&!empty($record)){
            M('star_wechat_group')->where($where)->setInc('sharenum');
            M('star_member')->where(array('star_member_id'=>$member_id))->setInc('money',$setinfo['sharegroup']);

            $mymoney =  M('star_member')->where(array('star_member_id'=>$member_id))->getField('money');
            $data['money'] = $mymoney;
            $data['repetition'] = 'no';
            $this->returnData($data,'分享成功',200);
        }


    }



    /**
     * 好友关联
     */
    public function friendsassociated(){

        $uid = I('post.my_member_id','','int');
        $coupling_uid = I('post.coupling_member_id','','int');
        $appid = I('post.appid','','htmlspecialchars');

        if ($uid==""||$coupling_uid==""){
            $this->returnData('','参数不能为空',401);
        }

        if ($uid==$coupling_uid){
            $this->returnData('','自己不用关联自己',100);
        }


        $where['my_member_id']=$uid;
        $where['coupling_member_id']=$coupling_uid;
        $where['appid'] = $appid;

        $where1['my_member_id']=$coupling_uid;
        $where1['coupling_member_id']=$uid;
        $where1['appid'] = $appid;

        $relevancy = M('star_relationship')->field('star_relationship_id')->where($where)->find();

        $relevancy1 = M('star_relationship')->field('star_relationship_id')->where($where1)->find();
        //判断是否已关联(有待优化)
        if ($relevancy||$relevancy1){
            $this->returnData('','已关联',200);
        }

        $data = array(
            'my_member_id'=>$uid,
            'coupling_member_id' =>$coupling_uid,
            'appid'=>$appid,
            'createtime' =>time(),
        );

        $insert = M('star_relationship')->data($data)->add();

        if ($insert){
            $this->returnData('','关联成功',200);
        }else{
            $this->returnData('','关联失败',100);
        }

    }

    /**
     * 获取题目进行挑战
     */
    public function challenge()
    {
        $member_id = I('post.member_id','','int');
        $state = I('post.state','','int');

        if (!$member_id){
            $this->returnData('','参数错误',401);
        }

        //一次取20题
        $nextcustoms = 20;
        //判断用户是否存在没完成题目
        $member_data    =   M('star_member')->field('customs,money,time')->where(array('star_member_id'=>$member_id))->find();

        if (empty($member_data))
        {
            $this->returnData('','用户不存在',400);
        }
        //继续获取题目
        if ($state=='2'){
            $time = I('post.time','','int');
            $sort = I('post.sort','','int');

            $starquestion = M('star_question')->limit($sort,$nextcustoms)->order('sort asc')->select();
            foreach ($starquestion as $key=>$value){

                $starquestion[$key]['imgsrc'] = $this->url.'star/'.$starquestion[$key]['imgsrc'];
            }
            $member_data['time'] = $time;
            $data['member_data'] = $member_data;
            $data['star_question'] = $starquestion;
            $this->returnData($data);
        }

        $customs = $member_data['customs'];

        //存在没有完成的题目，测返回该题目
        if (! empty($member_data['time']))
        {
            $customs = $customs-1;
        }

       //挑战新题目
       $starquestion = M('star_question')->limit($customs,$nextcustoms)->order('sort asc')->select();

        //存在没有完成的题目，备注
        if (! empty($member_data['time']))
        {
            $starquestion['0']['time'] = $member_data['time'];
            $starquestion['0']['continue'] = 'yes';
        }

        foreach ($starquestion as $key=>$value){

            $starquestion[$key]['imgsrc'] = $this->url.'star/'.$starquestion[$key]['imgsrc'];
        }

       $data['member_data'] = $member_data;
       $data['star_question'] = $starquestion;

       $this->returnData($data);

    }

    /***
     * 获取下次的题目
     */
    public function getnextquestion(){

        $sort = I('post.sort','','int');

        if (!$sort){
            $this->returnData('','参数错误',401);
        }
        $nextquestion = 5;
        $starquestion = M('star_question')->limit($sort,$nextquestion)->order('sort asc')->select();

        foreach ($starquestion as $key=>$value){

            $starquestion[$key]['imgsrc'] = $this->url.'star/'.$starquestion[$key]['imgsrc'];
        }

        $this->returnData($starquestion);

    }

    /**
     * 答题中
     */
    public function inanswer(){

        $member_id = I('post.member_id','','int');

        $state = I('post.state','','int');

        $money = I('post.money','','int');

        $appid = I('post.appid','','htmlspecialchars');

        if (!$member_id||!$state||!$money){
            $this->returnData('','参数错误',401);
        }


        //答对
        if ($state=='1'){
            $year   = date('Y');
            $week   = (int)date('W');

            $where  = array(
                'year'=>$year,
                'week'=>$week,
                'star_member_id'=>$member_id,
                'appid'=>$appid,
            );

            M('star_member')->where(array('star_member_id'=>$member_id))->setInc('money',$money);
            M('star_member')->where(array('star_member_id'=>$member_id))->setInc('customs');

            $isinweek = M('star_week')->field('star_week_id')->where($where)->find();
            if ($isinweek){
                M('star_week')->where($where)->setInc('getnum');
            }else{
                $member_data = M('star_member')->field('nickName,avatarUrl')->where(array('star_member_id'=>$member_id))->find();
                $data = array(
                    'year'=>$year,
                    'week'=>$week,
                    'star_member_id'=>$member_id,
                    'appid'=>$appid,
                    'createtime'=>date('Y-m-d H:i:s'),
                    'exittime'=>date('Y-m-d H:i:s'),
                    'getnum'=>'1',
                    'nickName'=>$member_data['nickname'],
                    'avatarUrl'=>$member_data['avatarurl'],
                );

                M('star_week')->data($data)->add();
            }

            $mymoney = M('star_member')->where(array('star_member_id'=>$member_id))->getField('money');
            $this->returnData(array('money'=>$mymoney));
        }
        //答错
        if ($state=='2'){
            $mymoney = M('star_member')->where(array('star_member_id'=>$member_id))->getField('money');
            if ($mymoney<$money){
                $this->returnData(array('enough'=>'no'),'金币不足',-1);
            }
            M('star_member')->where(array('star_member_id'=>$member_id))->setDec('money',$money);
            $mymoney = M('star_member')->where(array('star_member_id'=>$member_id))->getField('money');
            $this->returnData(array('money'=>$mymoney));
        }

        //金币复活
        if ($state=='3'){
            if ($money){
                $mymoney = M('star_member')->where(array('star_member_id'=>$member_id))->getField('money');
                //判断自身金币是否足够
                if ($mymoney<$money){
                    $this->returnData(array('enough'=>'no'),'金币不足',-1);
                }
                M('star_member')->where(array('star_member_id'=>$member_id))->setDec('money',$money); //减去对应的金币
                $this->returnData(array('enough'=>'yes'),'立即复活',200);
            }
            $this->returnData('','金币不能为空',401);

        }




    }

    /**
     * 退出
     */
    public function leave(){

        $member_id = I('post.member_id','','int');
        $sort = I('post.sort','','int');
        $time = I('post.time','','int');

        if (!$member_id||!$sort){
            $this->returnData('','参数错误',401);
        }

        $data = array(
            'customs'=>$sort,
            'time'=>$time,
        );
        M('star_member')->where(array('star_member_id'=>$member_id))->save($data);

        $this->returnData();

    }


    /**
     * 本周排行
     */
    public function getweek(){
        $member_id = I('post.member_id','','int');
        $year   = date('Y');
        $week   = (int)date('W');

        $where  = array(
            'star_member_id'=>$member_id
        );

        //用户排名数据
        $data['user_data']      =   array();
        $data['number_one']     =   array();     //第一名数据
        $data['number_two']     =   array();     //第二名数据
        $data['number_three']   =   array();     //第三名数据
        $data['user_data']  =   M('star_member')->where($where)->field('star_member_id,nickName,avatarUrl')->find();

        //用户默认初始值是0关
        if (! empty($data['user_data']))
        {
            $data['user_data']['getnum']    =   0;
        }

        //所有排名数据  ranking 名次
        $data['week_list']  = $this->getstarweek();

        if (! empty($data['week_list']))
        {
            $ranking    =   1;
            foreach ($data['week_list'] as $key =>$val)
            {
                if ($ranking == 1)
                {
                    $data['number_one'] =   $val;
                }
                elseif ($ranking == 2)
                {
                    $data['number_two'] =   $val;
                }
                elseif ($ranking == 3)
                {
                    $data['number_three']   =   $val;
                }

                $data['week_list'][$key]['ranking'] =   $ranking;

                if ($val['star_member_id'] == $data['user_data']['star_member_id'])
                {
                    $data['user_data']['ranking']  =    $ranking;
                    $data['user_data']['getnum']   =    $val['getnum'];
                }
                $ranking++;
            }
        }
        else
        {
            $data['user_data']['ranking']  =    '未上傍';
        }

        $this->returnData($data);
    }

    /**
     * 存放模板消息
     */
    public function send()
    {
        $appid = I('post.appid','','htmlspecialchars');
        $touser = I('post.touser','','htmlspecialchars');
        $page = I('post.page','','htmlspecialchars');
        $form_id = I('post.form_id','','htmlspecialchars');
        $form_type = I('post.form_type','','htmlspecialchars');
        $secret = I('post.secret','','htmlspecialchars');
        $member_id = I('post.member_id','','int');
        $template_id = I('post.template_id','','htmlspecialchars');

        if ($appid==""||$touser==""||$page==""||$form_id==""||$form_type==""||$secret==""){
            $this->returnData('','参数错误','401');
        }

        $date = date('Y-m-d');
        $insert = array(
            'appid'=>$appid,
            'touser'=>$touser,
            'template_id'=>$template_id,
            'page'=>$page,
            'form_id'=>$form_id,
            'form_type'=>$form_type?$form_type:1,
            'status'=>'-1',
            'add_time'=>time(),
            'secret'=>$secret,
            'createtime'=>$date,
            'star_member_id'=>$member_id,
        );

        M('star_template_send')->data($insert)->add();
        $this->returnData('成功','200');

        $where['touser'] = $touser;
        $where['template_id'] = $template_id;
        $where['createtime'] = $date;
        $where['status'] = '-1';

        $ishave = M('star_template_send')->field('wxopen_template_send_id')->where($where)->find();

        if ($ishave){
            M('star_template_send')->where(array('wxopen_template_send_id'=>$ishave['wxopen_template_send_id']))->save($insert);
        }else{
            M('star_template_send')->data($insert)->add();
        }

        $this->returnData('成功','200');

    }


    //广告数据
    private function get_ad_data()
    {
        $where['isshow'] = '1';
        $get_ad_data = M('star_appshow')->where($where)->select();
        foreach ($get_ad_data as $key=>$val){
            $get_ad_data[$key]['logo'] = $this->url.$get_ad_data[$key]['logo'];
            $get_ad_data[$key]['index'] = $key;
        }
        return $get_ad_data;
    }

    //获奖名单
    private function get_winner_data()
    {
        return array();
    }

    //奖品列表
    private function get_gift_data()
    {
        return array();
    }

    //其他游戏入口
    private function get_games_data()
    {
        return array();
    }

    //更多好玩
    private function get_more_data()
    {
        $more = M('star_moreplay')->where(array('isshow'=>'1'))->find();
        return $more;
    }



}